////////////////////////////////////////////////////////////////////////////////
//  COPYRIGHT (C) 2010 TELECOM DIGITAL MEDIA ("TDMEDIA").
//  ALL RIGHTS RESERVED.
//
//  THIS IS CONFIDENTIAL AND PROPRIETARY INTELLECTUAL PROPERTY OWNED BY AND
//  CREATED ON BEHALF OF TDMEDIA. ANY FORM OF DISTRIBUTION, COPY,
//  MODIFICATION WITHOUT THE WRITTEN CONSENT FROM TDMEDIA IS STRICTLY
//  PROHIBITED.
////////////////////////////////////////////////////////////////////////////////
package cc.telecomdigital.tdstock.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Process;
import android.view.View;
import cc.telecomdigital.tdstock.CommonDefn;
import cc.telecomdigital.tdstock.CustomizeDialog;
import cc.telecomdigital.tdstock.CustomizeDialogDualMax;
import cc.telecomdigital.tdstock.CustomizeDialogDualMax.IOnDialogButtonClick;
import cc.telecomdigital.tdstock.ITDLApplication;
import cc.telecomdigital.tdstock.R;
import cc.telecomdigital.tdstock.SystemInfo;
import cc.telecomdigital.tdstock.Framework.Activity_Framework;
import cc.telecomdigital.tdstock.Framework.UniqueItem.ScreenOrientationChangeListener.SCR_ORIENTATION;
import cc.telecomdigital.tdstock.Framework.UniqueItem.TDStockLog;
import cc.telecomdigital.tdstock.Http.H_CODE;
import cc.telecomdigital.tdstock.Http.Services.HttpAppInfo;
import cc.telecomdigital.tdstock.Services.LS_Authentication.LS_Authentication_Result;
import cc.telecomdigital.tdstock.Services.LS_UserClient.ILS_UserClient_Authentication_Report;
import cc.telecomdigital.tdstock.Services.LS_UserClient.LS_UserClient_Authentication_Result;
import cc.telecomdigital.tdstock.Services.TDStockReqFreeVerify.ITDStockReqFreeVerify_Result;
import cc.telecomdigital.tdstock.Services.TDStockReqFreeVerify.TDStockReqFreeVerify_Result;
import cc.telecomdigital.tdstock.activity.groups.more.push.client.Constants;
import cc.telecomdigital.tdstock.activity.groups.more.push.client.NotificationService;
import cc.telecomdigital.tdstock.activity.groups.more.push.client.ServiceManager;

/**
 * can add more animation in this screen
 * 
 * @author haibo
 * @desc modify by ouyangzhihui
 */
public class SplashActivity extends Activity_Framework
{
	private static String	TAG			= SplashActivity.class.getSimpleName();
	private Handler			_handler	= null;
	private SharedPreferences	_prefs	= null;
	private CustomizeDialog customDialog;
	
	private static ServiceManager serviceManager;

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.splash);
		setDefaultOrientation();
		_handler = new Handler();
		
		/**
		 * hunter,2011-10-13,开始推送消息服务
		 */
		if(serviceManager == null) 
		{
			serviceManager = new ServiceManager(this);
			serviceManager.setNotificationIcon(R.drawable.favicon);
		}
		

		TDStockLog.d(TAG, "create a new instance !");
		// Transfer this onResume, since our app will not exit and could be
		// restart when in background
		// SetActivityToTop();
	}

	private void setDefaultOrientation()
	{	
		//Save into memory
		int tmpOrientation = getRequestedOrientation();

		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);

		int               rotation, width, height;
		
		rotation = displayObj.getOrientation();
		width = 0;
		height = 0;
		TDStockLog.i(GetIdentity(), "Rotation Value=" + rotation);		
		switch (rotation)
		{
			case 0:
				TDStockLog.i(GetIdentity(), "Rotation is: 0 or 180");
				width  = fScrWidthPixel;
				height = fScrHeightPixel;
				break;       
			default:
				TDStockLog.i(GetIdentity(), "Rotation is: 90 or 270");
				width  = fScrHeightPixel;
				height = fScrWidthPixel;
				break;
		}

		if(width > height)
		{
			appHost.SetInitOrientation(SCR_ORIENTATION.LANDSCAPE);
			TDStockLog.i(GetIdentity(), "*** Natural Orientation is landscape, isInvese=true");			
		}
		else
		{
			appHost.SetInitOrientation(SCR_ORIENTATION.PORTRAIT);			
			TDStockLog.i(GetIdentity(), "*** Natural Orientation is portrait, isInverse=false");
		}
		setRequestedOrientation(tmpOrientation);
	}

	public void exitApp()
	{
		finish();
		Process.killProcess(Process.myPid());
	}

	@Override
	public void onPause()
	{
		if(customDialog != null)
		{
			customDialog.dismiss();
		}
		super.onPause();
	}

	@Override
	public void onResume()
	{
		
		new Thread() 
		{
			public void run() 
			{
				if(appHost != null)
					appHost.LSClient_Reset();
			}
		}.start();
		

		super.onResume();
		// Andy
		// Make this at the top as always, once restart, other will be restart
		SetActivityToTop();
		
		initApp(); // haibo, 2011-08-02, set as production environment;
		
		
		  boolean result = goThroughNotificaitonTunnelIfPossiable();
		  if(result) 
		  {
		    	return ;
		  }
		
		if (((ITDLApplication) getApplicationContext()).isExitApp())
		{
			exitApp();
		}
		else
		{
			final Runnable job = new Runnable()
			{
				public void run()
				{
					AutoLoginApp();
				}
			};
		/*	new Thread()
			{
				public void run()
				{*/
					_handler.post(job);
		/*		}
			}.start();*/
		}
	}

	private void TrialQueryAuth(final String iActivateCode)
	{
		appHost.LS_RequestFreeTrialVerifiy(new ITDStockReqFreeVerify_Result()
		{
			@Override
			public void TDStockReqFreeVerify_Response(TDStockReqFreeVerify_Result iResult)
			{
				if (iResult.successfulSend && "0".equals(iResult.statusCode))
				{
					// VerifyActiveCodeActivity.activeCode = iActivateCode;
					// 自動登錄
					// Intent intent = new Intent(getApplicationContext(),
					// VerifyActiveCodeActivity.class);
					// intent.setFlags(Intent.FLAG_ACTIVITY_NO_USER_ACTION);
					// SwitchForwardActivity(VerifyActiveCodeActivity.class,
					// intent);

					TrialAutoLogonToApp(iActivateCode);
				}
				else
				{
					TDLDemoAutoLogonToDelayModeApp();
				}
			}
		});
	}

	private void AutoLoginApp()
	{
		if (!SystemInfo.isNetworkingConnected(this))
		{
			// 沒有網絡連接，進入登錄頁面以提示用戶。
//			forwardToAccountLogin(null);
			// 网络未连接...
			customDialog = new CustomizeDialog(this, getResources().getString(R.string.info), "無法連接到伺服器，網絡可能出現問題。請檢查你的網絡連接並移動至網絡訊號穩定的地方再做嘗試。", getResources().getString(R.string.ok), false)
			{
				@Override
				public void onClick(View v)
				{
					if (v == okButton)
					{
						dismiss();
						exitApp();
					}
				}
			};
			customDialog.show();
			return; // 网络未连接...
		}

		if (_prefs == null)
		{
			_prefs = getSharedPreferences(CommonDefn.SYSTEM_CURRENT_SETTING, Context.MODE_PRIVATE);
		}

		if (_prefs == null)
		{
			// 拿不到數據
			TDLDemoAutoLogonToDelayModeApp();
			return;
		}

		boolean isAutoLogin = _prefs.getBoolean(CommonDefn.PREFERENCE_IS_AUTO_LOGIN_APP, false);
		TDStockLog.d(TAG, "autoLogin=" + isAutoLogin);
		// 是否自动登录
		if (isAutoLogin)
		{
			String user = _prefs.getString(CommonDefn.PREFERENCE_LAST_ACCOUNT_NAME, "");
			String pwd = _prefs.getString(CommonDefn.PREFERENCE_LAST_ACCOUNT_PWD, "");

			// boolean isSendActiveCode =
			// _prefs.getBoolean(CommonDefn.PREFERENCE_IS_SEND_ACTIVE_CODE,
			// false);

			String activeCode = _prefs.getString(CommonDefn.PREFERENCE_TRIAL_ACTIVE_CODE, "");

			// 使用已经登入过的用户名密码自动登入(是否存在用户名密码)
			if (!"".equals(user) && !"".equals(pwd))
			{
//				CustomerInfo.setDataMode(CommonDefn.DataMode.Realtime);
				// forwardToAccountLogin();
				AccountAutoLogonToApp(user, pwd);
			}
			else if (/* isSendActiveCode && */!"".equals(activeCode))
			{
				// 试用验证码自动登入(是否试用，并未过期)
				TrialQueryAuth(activeCode);
				return;
			}
			else
			{ 
				// 不存在用户名密码 和 无试用或试用已过期，进入延迟模式
				TDLDemoAutoLogonToDelayModeApp();
			}
		}
		else
		{
			// 不自动登录，进入延迟模式
			TDLDemoAutoLogonToDelayModeApp();
		}
	}

	/**
	 * 進入程序主界面
	 */
	private void forwardToMainActivity()
	{
		Intent forwardToMainActivity = new Intent(getApplicationContext(), RealtimeStockActivity.class);
		forwardToMainActivity.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NO_USER_ACTION);
		TDStockLog.d(TAG, "***** forwarding to RealtimeStockActivity!");
		RealtimeStockActivity.SetTabIndex(RealtimeStockActivity.TAB_INDEX_STOCK);
		SwitchForwardActivity(RealtimeStockActivity.class, forwardToMainActivity);
	}

	/**
	 * 用戶名密碼登錄
	 */
	private void forwardToAccountLogin(String iErrorMessage)
	{
		AccountLoginActivity.errorMessage = iErrorMessage;
		
		Intent intent = new Intent(getApplicationContext(), AccountLoginActivity.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NO_USER_ACTION);
		TDStockLog.d(TAG, "***** forwarding to login page!");
		SwitchForwardActivity(AccountLoginActivity.class, intent);
	}

	@Override
	protected void onRestart()
	{
		super.onRestart();

		if (((ITDLApplication) getApplicationContext()).isExitApp())
		{
			exitApp();
		}
	}

	// set defalut state for the customer
	private void initApp()
	{
		// Let the Application handle this setting
		// CustomerInfo.setEnvironment(CommonDefn.Environment.Production);
		// only this place to change the environment, Notes: must set as
		// Production Environment before publish it.
		// set defalt mode as realtime, Notes: only hit delay button to change
		// the mode.
//		CustomerInfo.setDataMode(CommonDefn.DataMode.Realtime);
//		CustomerInfo.version_number = SystemInfo.getAppVersionName(this);

		((ITDLApplication) getApplicationContext()).setAdShowed(false);
		CustomizeDialog.dismissAll();
	}
	
	private void TrialAutoLogonToApp(String iActivateCode)
	{
		AutoLoginToApp(null, null, iActivateCode, CommonDefn.ModeType.ACTIVECODE);
	}
	private void TDLDemoAutoLogonToDelayModeApp()
	{
		AutoLoginToApp(CommonDefn.ACCOUNT_USER_NAME_TRIAL_DELAY, CommonDefn.ACCOUNT_USER_PWD_TRIAL_DELAY, null, CommonDefn.ModeType.DELARY);
	}
	private void AccountAutoLogonToApp(String iUserName, String iPassword)
	{
		AutoLoginToApp(iUserName, iPassword, null, CommonDefn.ModeType.ACCOUNTLOGIN);
	}

	private void AutoLoginToApp(final String userName, final String password, final String activateCode, final CommonDefn.ModeType iModeType)
	{
		TDStockLog.d(TAG, "AutoLoginMode=>" + iModeType);
		H_CODE statusCode;
		ILS_UserClient_Authentication_Report report = new ILS_UserClient_Authentication_Report()
		{
			@Override
			public void LS_UserClient_Authentication_Response(LS_UserClient_Authentication_Result iResponse)
			{
				TDStockLog.d(TAG, "AutoLogonToApp=>callback: statusCode=" + iResponse.statusCode + ", errMsg="+iResponse.errorMessage);
				if ((iResponse == null) || (iResponse.successfulSend == false) || (iResponse.statusCode == null))
				{
					if(CommonDefn.ModeType.ACCOUNTLOGIN == iModeType)
					{
						AccountLoginActivity.iUserName = userName;
						AccountLoginActivity.iPassword = password;
					}
//					Toast.makeText(actContext, "登錄失敗!", Toast.LENGTH_SHORT).show();
//					forwardToAccountLogin(iResponse==null?getResources().getString(R.string.login_failure):iResponse.errorMessage);
					forwardToAccountLogin(getString(R.string.login_failure));					
					return;
				}

				if ((iResponse.statusCode == null) || !iResponse.statusCode.equals("0"))
				{
					if(CommonDefn.ModeType.ACCOUNTLOGIN == iModeType)
					{
						AccountLoginActivity.iUserName = userName;
						AccountLoginActivity.iPassword = password;
					}
//					Toast.makeText(actContext, "登錄失敗:" + " statusCode=" + iResponse.statusCode + ", errMsg=" + iResponse.errorMessage, Toast.LENGTH_SHORT).show();
					
					((ITDLApplication) getApplicationContext()).putInt(CommonDefn.PREFERENCE_AUTO_LOGIN_FAIL_COUNTER, ITDLApplication.DEFAULT_INT_VALUE);
				    //Kick out
					if (iResponse.statusCode != null && "101".equals(iResponse.statusCode))
					{
						final String            extraContent;
						CustomizeDialogDualMax  msgDialog;
						
						msgDialog = new CustomizeDialogDualMax(actContext);
						msgDialog.SetOnCancelFeature(false, null);
						
						msgDialog.SetHeader(getString(R.string.info));
						msgDialog.SetMsgContent(iResponse.errorMessage);
						
						//Create a downloadable message if needed
						extraContent = iResponse.linkContent;
						if ((extraContent != null) && (extraContent.length() != 0 ))
						{
							msgDialog.SetDualButton( iResponse.linkCaption, 
												 new IOnDialogButtonClick()
												{
													@Override
													public void OnResponse()
													{
														Uri    uriObj;
														Intent intentObj;
														String linkContent;
										
														linkContent = extraContent;					
														if ((linkContent == null) || (linkContent.length() == 0))
															return;
														
														intentObj = new Intent(Intent.ACTION_VIEW);
														uriObj = Uri.parse(linkContent);
														intentObj.setData(uriObj);
														startActivity(intentObj);
													}				
												},
												getString(R.string.ok),
												new IOnDialogButtonClick()
												{
													@Override
													public void OnResponse()
													{
														exitApp();
													}													
												});
						}			
						else
						{
							msgDialog.SetSingleButton(getString(R.string.ok), 
											new IOnDialogButtonClick()
											{
												@Override
												public void OnResponse()
												{
													exitApp();
												}													
											});
						}
						msgDialog.show();
						
//						//server response message;
//						new CustomizeDialog(SplashActivity.this, getResources().getString(R.string.info), iResponse.errorMessage.trim(), getResources().getString(R.string.ok), false)
//						{
//							@Override
//							public void onClick(View v)
//							{
//								if(v == okButton)
//								{
//									dismiss();
//									exitApp();
//								}
//							}
//						}.show();
					}
					else
					{
						forwardToAccountLogin(iResponse.errorMessage);
					}
					return;
				}

				if (iResponse.statusCode.equals("0"))
				{
//					if(CommonDefn.ModeType.ACCOUNTLOGIN != iModeType)
					if(!iResponse.errorMessage.trim().equals(""))
						BaseActivity.loginResult = new LS_Authentication_Result(iResponse);						

					SystemInfo.initLoginApp(getApplicationContext(), iModeType, userName, password, null, null);
					((ITDLApplication) getApplicationContext()).SetServicePlan(appHost.GetLSClient_ServicePlan());
					forwardToMainActivity();
					return;
				}
			}
		};
		
		if(CommonDefn.ModeType.ACTIVECODE == iModeType)
		{
			statusCode = HttpAppInfo.SendFrameworkTrialAuthRequest(activateCode, report);
		}
		else
		{
			statusCode = HttpAppInfo.SendFrameworkILoginAuthRequest(userName, password, report);
		}
		
		TDStockLog.d(TAG, "AutoLogonToApp=>status:" + statusCode);
		if(statusCode != H_CODE.OK)
		{
			if(CommonDefn.ModeType.ACCOUNTLOGIN == iModeType)
			{
				AccountLoginActivity.iUserName = userName;
				AccountLoginActivity.iPassword = password;
			}
			forwardToAccountLogin(getResources().getString(R.string.login_failure));
		}
	}
	
	
	/**
	 * 根据flag确定是否重启服务
	 * 
	 * @param flag
	 */
	public static void startService(boolean flag) {
		NotificationService.flag = flag;
		serviceManager.startService(TAG);
	    TDStockLog.d(TAG, "重启成功1");
	}

	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		//getIntent().putExtras(intent);
		setIntent(intent);
		TDStockLog.d(TAG, "The app is restarting！");
	}
	
	
	private boolean goThroughNotificaitonTunnelIfPossiable()
	{
		Intent intent = new Intent(this, RealtimeStockActivity.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_NO_USER_ACTION);
		intent.putExtra(Constants.INTENT_KEY_GO_NOTIFICATION_TUNNEL, true);
		//第一次启动
		if (RealtimeStockActivity.tabHost == null)
		{
			return false;
		}
		//第二次之后的启动
		else
		{

			if (getIntent().getStringExtra(Constants.INTENT_KEY_MESSAGE_ID) == null)
			{
				return false;
			}
			else
			{
				String messageId = getIntent().getStringExtra(
						Constants.INTENT_KEY_MESSAGE_ID);
				String messageTypeId = getIntent().getStringExtra(
						Constants.INTENT_KEY_MESSAGE_TYPE_ID);
				intent.putExtra(Constants.INTENT_KEY_MESSAGE_ID, messageId);
				intent.putExtra(Constants.INTENT_KEY_MESSAGE_TYPE_ID,
						messageTypeId);
			}
			if (RealtimeStockActivity.tabHost != null
					&& RealtimeStockActivity.tabHost.getCurrentTab() != 4)
			{
				intent.putExtra(Constants.INTENT_KEY_ISGO_MOREACTIVITY,
						true);
			}
			else
			{
				intent
						.putExtra(
								Constants.INTENT_KEY_ISSETTING_CURRUCT_TABMOREACTIVITY,
								true);
			}
			startActivity(intent);
			return true;
		}

	}

	public static void oneOfStart(Activity context, Intent intent)
	{

		String messageId = context.getIntent().getStringExtra(
				Constants.INTENT_KEY_MESSAGE_ID);
		//普通启动
		if (messageId == null)
		{
			TDStockLog.d(TAG, "Start");

		}
		//通知启动
		else
		{
			TDStockLog.d(TAG, "Notification Start");
			String temp = "".equals(messageId) ? "空" : messageId;
			TDStockLog.d(TAG, "messageId  is " + temp);
			//list UI
			if ("".equals(messageId))
			{

			}
			//detail UI
			else
			{
				String messageTypeId = context.getIntent().getStringExtra(
						Constants.INTENT_KEY_MESSAGE_TYPE_ID);
				intent.putExtra(Constants.INTENT_KEY_MESSAGE_TYPE_ID,
						messageTypeId);
			}
			intent.putExtra(Constants.INTENT_KEY_MESSAGE_ID, messageId);
			if (RealtimeStockActivity.tabHost != null
					&& RealtimeStockActivity.tabHost.getCurrentTab() != 4)
			{
				intent.putExtra(Constants.INTENT_KEY_ISGO_MOREACTIVITY,
						true);
			}
			else
			{
				intent
						.putExtra(
								Constants.INTENT_KEY_ISSETTING_CURRUCT_TABMOREACTIVITY,
								true);
			}
		}
	}
	
}
